package com.pig4cloud.pig.module.controller.charger;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.charger.*;
import com.pig4cloud.pig.module.api.entity.dto.ChargerOrderDTO;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.charger.IChargerOrderService;
import com.pig4cloud.pig.module.service.charger.IChargerPortRecordService;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2022-05-07
 */
@Validated
@Api(value = "订单控制器", tags = {"订单管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/charger/order")
public class ChargerOrderController {

    private final IChargerOrderService chargerOrderService;
	private final IEstateService estateService;
	private final IChargerPortRecordService chargerPortRecordService;
	private final IWxUserService wxUserService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询订单列表
     */
    @ApiOperation("查询订单列表")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
    @GetMapping("/list")
    public TableDataInfo<ChargerOrder> list(@Validated ChargerOrder chargerOrder) {
        QueryWrapper<ChargerOrder> qw = new QueryWrapper<>();

		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(chargerOrder.getEstateId()!=null){
				qw.eq("estate_id",chargerOrder.getEstateId());
			}
		}

		if(chargerOrder.getStatus()!=null){
			if(chargerOrder.getStatus() == 6){
				qw.eq("status",chargerOrder.getStatus()).or().eq("refund_status",3);
			}else {
				qw.eq("status", chargerOrder.getStatus());
			}
		}

		if(chargerOrder.getPayPlatform()!=null){
			qw.eq("pay_platform",chargerOrder.getPayPlatform());
		}

		if(chargerOrder.getDeviceId()!=null){
			qw.eq("device_id",chargerOrder.getDeviceId());
		}
		if(StrUtil.isNotEmpty(chargerOrder.getDeviceSn())){
			qw.eq("device_sn",chargerOrder.getDeviceSn());
		}

		if(chargerOrder.getOrderNo()!=null){
			qw.eq("order_no",chargerOrder.getOrderNo()).or().like("nick_name",chargerOrder.getOrderNo());
		}
		if(StrUtil.isNotEmpty(chargerOrder.getBeginDate())){
			qw.between("create_time",chargerOrder.getBeginDate() + " 00:00:00",chargerOrder.getEndDate() + " 23:59:59");
		}

		qw.orderByDesc("create_time");

        TableDataInfo<ChargerOrder> td = PageUtils.buildDataInfo(chargerOrderService.page(PageUtils.buildPage(),qw));
        List<ChargerOrder> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (ChargerOrder order : list){
				Estate estate = estateService.findById(order.getEstateId());
				if(estate!=null){
					order.setEstateName(estate.getEstateName());
				}
				WxUser wxUser = wxUserService.findById(order.getUserId());
				if(wxUser!=null){
					order.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0){
						order.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
				if(StrUtil.isNotEmpty(order.getNickName())){
					order.setNickName(EmojiParser.parseToUnicode(order.getNickName()));
				}
			}
		}

		Map<String,Object> mapCharger = new HashMap<>();
		if(chargerOrder.getEstateId()!=null){
			mapCharger.put("estate_id",chargerOrder.getEstateId());
		}

		if(StrUtil.isNotEmpty(chargerOrder.getBeginDate())){
			mapCharger.put("begin_time",chargerOrder.getBeginDate() + " 00:00:00");
			mapCharger.put("end_time",chargerOrder.getEndDate() + " 23:59:59");
		}
		ChargerOrderDTO chargerOrderDTO = chargerOrderService.selectOrderTongjiByEstateId(mapCharger);
		Map<String,Object> mapOther = new HashMap<>();
		mapOther.put("tongji",chargerOrderDTO);
		td.setOtherData(mapOther);
        return td;
    }


	/**
	 * 查询订单列表
	 */
	@ApiOperation("查询充电记录列表")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/record/data/list")
	public TableDataInfo<ChargerPortRecord> recordList(@Validated ChargerOrder chargerOrder) {


//		QueryWrapper<ChargerPortRecord> qw = new QueryWrapper<>();
//		if(chargerOrder.getDeviceId()!=null){
//			qw.eq("charger_id",chargerOrder.getDeviceId());
//		}
//		if(StrUtil.isNotEmpty(chargerOrder.getDeviceSn())){
//			qw.eq("charger_sn",chargerOrder.getDeviceSn());
//		}
//
//		if(chargerOrder.getOrderNo()!=null){
//			qw.eq("order_no",chargerOrder.getOrderNo());
//		}
//		qw.orderByAsc("create_time");

		TableDataInfo<ChargerPortRecord> td = new TableDataInfo<>();// PageUtils.buildDataInfo(chargerPortRecordService.getRecordListByOrderNo(PageUtils.buildPage(),chargerOrder));
		List<ChargerPortRecord> list = chargerPortRecordService.getRecordListByOrderNo(chargerOrder);
		td.setData(list);
		return td;
	}


	/**
	 * 查询订单列表
	 */
	@ApiOperation("查询订单列表")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/tongjiList")
	public TableDataInfo<ChargerOrderDTO> tongjiList(@Validated ChargerOrder chargerOrder) {
		Map<String,Object> map = new HashMap<>();

		if(chargerOrder.getEstateId()!=null){
			map.put("estate_id",chargerOrder.getEstateId());
		}

		if(chargerOrder.getPayPlatform()!=null){
			map.put("pay_platform",chargerOrder.getPayPlatform());
		}

		/*String beginDate = "", endDate = "";
		if(StrUtil.isNotEmpty(chargerOrder.getBeginDate())){
			beginDate = DateUtils.getDate();
		}else {
			beginDate = chargerOrder.getBeginDate();
		}

		if(StrUtil.isNotEmpty(chargerOrder.getEndDate())){
			endDate = DateUtils.getDate();
		}else {
			endDate = chargerOrder.getEndDate();
		}*/

		map.put("beginTime",chargerOrder.getBeginDate() + " 00:00:00");
		map.put("endTime",chargerOrder.getEndDate() + " 23:59:59");

		TableDataInfo<ChargerOrderDTO> td = PageUtils.buildDataInfo(chargerOrderService.selectChargerOrderTongji(PageUtils.buildPage(),map));
		return td;
	}

    /**
     * 导出订单列表
     */
    @ApiOperation("导出订单列表")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:export')")
    @SysLog("订单")
    @GetMapping("/export")
    public List export(@Validated ChargerOrder chargerOrder) {
		QueryWrapper<ChargerOrder> qw = new QueryWrapper<>();

		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(chargerOrder.getEstateId()!=null){
				qw.eq("estate_id",chargerOrder.getEstateId());
			}
		}

		if(chargerOrder.getDeviceId()!=null){
			qw.eq("device_id",chargerOrder.getDeviceId());
		}

		if(StrUtil.isNotEmpty(chargerOrder.getDeviceSn())){
			qw.eq("device_sn",chargerOrder.getDeviceSn());
		}

		if(chargerOrder.getOrderNo()!=null){
			qw.eq("order_no",chargerOrder.getOrderNo());
		}

		if(chargerOrder.getPayPlatform()!=null){
			qw.eq("pay_platform",chargerOrder.getPayPlatform());
		}
//		if(StrUtil.isNotEmpty(chargerOrder.getBeginDate())){
//			qw.between("create_time",chargerOrder.getBeginDate() + " 00:00:00",chargerOrder.getEndDate() + " 23:59:59");
//		}


		String beginDate = "", endDate = "";
		if(chargerOrder.getBeginDate() == null){
			beginDate = DateUtils.getDate();
		}else {
			beginDate = chargerOrder.getBeginDate();
		}

		if(chargerOrder.getEndDate()== null){
			endDate = DateUtils.getDate();
		}else {
			endDate = chargerOrder.getEndDate();
		}

		qw.between("create_time",beginDate + " 00:00:00",endDate + " 23:59:59");

		qw.orderByDesc("create_time");

        List<ChargerOrder> list = chargerOrderService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (ChargerOrder order : list){
				Estate estate = estateService.findById(order.getEstateId());
				if(estate!=null){
					order.setEstateName(estate.getEstateName());
				}

				if(StrUtil.isNotEmpty(order.getNickName())){
					order.setNickName(EmojiParser.parseToUnicode(order.getNickName()));
				}
				if(order.getStartChargerTime()!=null){
					order.setStartChargerTimeStr(DateUtils.getTime(order.getStartChargerTime()));
				}

				if(order.getEndChargerTime()!=null){
					order.setEndChargerTimeStr(DateUtils.getTime(order.getEndChargerTime()));
				}

				if(order.getCreateTime()!=null){
					order.setCreateTimeStr(DateUtils.getTime(order.getCreateTime()));
				}

				//订单状态 0 - 未支付   1 - 支付中  2 - 已支付  3 - 充电中  4 - 已发起退款  5 - 退款完成  6 - 退款失败  7 - 订单已完成（结束） 8 -  订单取消
				if(order.getStatus() == 0){
					order.setStatusStr("待支付");
				} else if(order.getStatus() == 1){
					order.setStatusStr("支付中");
				} else if(order.getStatus() == 2){
					order.setStatusStr("已支付");
				} else if(order.getStatus() == 3){
					order.setStatusStr("充电中");
				} else if(order.getStatus() == 4){
					order.setStatusStr("已发起退款");
				} else if(order.getStatus() == 5){
					order.setStatusStr("退款完成");
				} else if(order.getStatus() == 6){
					order.setStatusStr("退款失败");
				} else if(order.getStatus() == 7){
					order.setStatusStr("订单已完成");
				} else if(order.getStatus() == 8){
					order.setStatusStr("订单取消");
				}
			}
		}
        // ExcelUtil<ChargerOrder> util = new // ExcelUtil<ChargerOrder>(ChargerOrder.class);
        return  list;// util.exportExcel(list, "订单");
    }


	/**
	 * 导出订单列表
	 */
	@ApiOperation("导出订单列表")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:export')")
	@SysLog("订单")
	@GetMapping("/exportTongji")
	public List exportTongji(@Validated ChargerOrder chargerOrder) {
		Map<String,Object> map = new HashMap<>();
		if(chargerOrder.getEstateId()!=null){
			map.put("estate_id",chargerOrder.getEstateId());
		}

		if(chargerOrder.getPayPlatform()!=null){
			map.put("pay_platform",chargerOrder.getPayPlatform());
		}

		String beginDate = "", endDate = "";
		if(chargerOrder.getBeginDate() == null){
			beginDate = DateUtils.getDate();
		}else {
			beginDate = chargerOrder.getBeginDate();
		}

		if(chargerOrder.getEndDate()== null){
			endDate = DateUtils.getDate();
		}else {
			endDate = chargerOrder.getEndDate();
		}

		map.put("beginTime",beginDate + " 00:00:00");
		map.put("endTime",endDate + " 23:59:59");


		List<ChargerOrderDTO> list = chargerOrderService.selectChargerOrderTongji(map);
		if(CollUtil.isNotEmpty(list)){
			for (ChargerOrderDTO orderDTO : list){
				orderDTO.setMonth(beginDate.substring(0,7));
			}
		}
		// ExcelUtil<ChargerOrderDTO> util = new // ExcelUtil<>(ChargerOrderDTO.class);
		return  list;// util.exportExcel(list, "小区充电订单统计");
	}


	/**
     * 获取订单详细信息
     */
    @ApiOperation("获取订单详细信息")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:query')")
    @GetMapping("/{id}")
    public R<ChargerOrder> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ChargerOrder chargerOrder = chargerOrderService.getById(id);
        if(chargerOrder!=null){
			List<String> times = new ArrayList<>();
			List<Double> values = new ArrayList<>();
			List<ChargerPortRecord> list = chargerPortRecordService.getRecordListByOrderNo(chargerOrder);
			if(CollUtil.isNotEmpty(list)){
				for (ChargerPortRecord portRecord : list){
					if(portRecord.getPower()!=null){
						String time = DateUtils.getSimpleTime(portRecord.getCreateTime());
						times.add(time);
						values.add(portRecord.getPower());
					}
				}
			}
			chargerOrder.setTimes(times);
			chargerOrder.setValues(values);
			chargerOrder.setRecords(list);
		}
        return R.ok(chargerOrder);
    }

    /**
     * 新增订单
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:add')")
    @SysLog("订单")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ChargerOrder chargerOrder) {
        return R.okByRow(chargerOrderService.save(chargerOrder) ? 1 : 0);
    }

    /**
     * 修改订单
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:edit')")
    @SysLog("订单")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ChargerOrder chargerOrder) {
        return R.okByRow(chargerOrderService.updateById(chargerOrder) ? 1 : 0);
    }

	/**
	 * 订单退款
	 */
	@ApiOperation("订单退款")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:edit')")
	@SysLog("订单退款")

	@PostMapping("/refundOrder")
	public R<Void> refundOrder(@Valid @RequestBody ChargerOrder chargerOrder) {
		return R.okByRow(chargerOrderService.refundChargerOrder(chargerOrder));
	}

	/**
	 * 订单退款查询
	 */
	@ApiOperation("订单退款查询")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:edit')")

	@GetMapping("/queryRefund/{id}")
	public R<Void> queryRefund(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		ChargerOrder chargerOrder = chargerOrderService.getById(id);
		if(chargerOrder!=null){
			chargerOrderService.queryRefundChargerOrder(chargerOrder);
		}
		return R.okByRow(1);
	}


    /**
     * 删除订单
     */
    @ApiOperation("删除订单")
    @PreAuthorize("@pms.hasPermission('module:chargerorder:remove')")
    @SysLog("订单")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable String[] ids) {
        return R.okByRow(chargerOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

	@ApiOperation("查询充电记录")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/dianliangList")
	public TableDataInfo<ChargerUsedBattery> dianliangList(@Validated ChargerUsedBattery chargerUsedBattery) {
		Map<String,Object> map = new HashMap<>();
		if (chargerUsedBattery.getEstateId()!=null){
			map.put("estate_id",chargerUsedBattery.getEstateId());
		}
		if (chargerUsedBattery.getBeginTime()!=null && chargerUsedBattery.getEndTime()!=null){
			map.put("beginTime",chargerUsedBattery.getBeginTime() + " 00:00:00");
			map.put("endTime",chargerUsedBattery.getEndTime() + " 23:59:59");
		}
		TableDataInfo<ChargerUsedBattery> td = PageUtils.buildDataInfo(chargerOrderService.selectChargerUsedBattery(PageUtils.buildPage(),map));
		List<ChargerUsedBattery> list = td.getData();
		for (ChargerUsedBattery list1:list){
			td.setTotal(list1.getTotals());
			if (list1.getEstateId()!=null){
				Estate estate = estateService.getById(list1.getEstateId());
				if (ObjectUtil.isNotEmpty(estate)){
					list1.setEstateName(estate.getEstateName());
				}
			}
		}

		return td;
	}

	@ApiOperation("查询充电接口记录")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/jiekouList")
	public TableDataInfo<ChargerOrderDetailedList> jiekouList(@Validated ChargerOrderDetailedList chargerOrderDetailedList) {
		Map<String,Object> map = new HashMap<>();
		if (ObjectUtil.isNotEmpty(chargerOrderDetailedList.getDeviceId())){
			map.put("device_id",chargerOrderDetailedList.getDeviceId());
		}
		if (chargerOrderDetailedList.getBeginTime()!=null && chargerOrderDetailedList.getEndTime()!=null){
			map.put("beginTime",chargerOrderDetailedList.getBeginTime() + " 00:00:00");
			map.put("endTime",chargerOrderDetailedList.getEndTime() + " 23:59:59");
		}
		TableDataInfo<ChargerOrderDetailedList> td = PageUtils.buildDataInfo(chargerOrderService.selectChargerOrderDetailedList(map));
		return td;
	}


	@ApiOperation("查询小区充电量记录")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/estateChargerList")
	public List estateChargerList(@Validated ChargerEstateBattery ChargerEstateBattery) {
		Map<String,Object> map = new HashMap<>();
		if (ChargerEstateBattery.getBeginTime()!=null && ChargerEstateBattery.getEndTime()!=null){
			map.put("beginTime",ChargerEstateBattery.getBeginTime() + " 00:00:00");
			map.put("endTime",ChargerEstateBattery.getEndTime() + " 23:59:59");
		}
		TableDataInfo<ChargerEstateBattery> td = PageUtils.buildDataInfo(chargerOrderService.selectChargerEstateBattery(map));
		List<ChargerEstateBattery> list=td.getData();
		List ret = new ArrayList();
		ArrayList<String> estateName = new ArrayList();
		ArrayList<Integer> orderQuantity = new ArrayList();
		ArrayList<Integer> usePrice = new ArrayList();
		ArrayList<Integer> payBattery = new ArrayList();
		for (ChargerEstateBattery list1:list){
			if (list1.getEstateId()!=null){
				Estate estate = estateService.getById(list1.getEstateId());
				if (ObjectUtil.isNotEmpty(estate)){
					estateName.add(estate.getEstateName());
				}
			}
			orderQuantity.add(list1.getOrderQuantity());
			usePrice.add(list1.getUsePrice());
			payBattery.add(list1.getPayBattery());
		}
		ret.add(estateName);
		ret.add(orderQuantity);
		ret.add(usePrice);
		ret.add(payBattery);
		return ret;
	}

	@ApiOperation("查询小区充电量记录")
	@PreAuthorize("@pms.hasPermission('module:chargerorder:list')")
	@GetMapping("/shebeiChargerList")
	public List shebeiChargerList(@Validated ChargerUsedBattery chargerUsedBattery) {
		Map<String,Object> map = new HashMap<>();
		if (chargerUsedBattery.getEstateId()!=null){
			map.put("estate_id",chargerUsedBattery.getEstateId());
		}
		if (chargerUsedBattery.getBeginTime()!=null && chargerUsedBattery.getEndTime()!=null){
			map.put("beginTime",chargerUsedBattery.getBeginTime() + " 00:00:00");
			map.put("endTime",chargerUsedBattery.getEndTime() + " 23:59:59");
		}
		TableDataInfo<ChargerUsedBattery> td = PageUtils.buildDataInfo(chargerOrderService.selectChargerUsedBattery(PageUtils.buildPage(),map));
		List<ChargerUsedBattery> list=td.getData();
		List ret = new ArrayList();
		ArrayList<String> name = new ArrayList();
		ArrayList<Integer> orderQuantity = new ArrayList();
		ArrayList<Integer> usePrice = new ArrayList();
		ArrayList<Integer> payBattery = new ArrayList();
		for (ChargerUsedBattery list1:list){
			name.add(list1.getDeviceName());
			orderQuantity.add(list1.getOrderQuantity());
			usePrice.add(list1.getUsePrice());
			payBattery.add(list1.getPayBattery());
		}
		ret.add(name);
		ret.add(orderQuantity);
		ret.add(usePrice);
		ret.add(payBattery);
		return ret;
	}

}
